import 'package:get/get.dart';
import '../../../entity/home/content/new_zone__entity.dart';
import '../../http/network.dart';

class DecorationNewZoneCtr extends GetxController {
  var newZoneGoodsList = <NewZoneEntity>[].obs; // 所有商品列表
  var displayedGoodsList = <NewZoneEntity>[].obs; // 当前展示的商品列表

  int _currentBatchStartIndex = 0; // 当前批次的起始索引
  final int _itemsPerBatch = 3; // 每批次展示的数量

  void fetchData(Map<String, dynamic> info) {
    if (info['new_zone_source'] == '0') {
      fetchRecentlyMarketingGoods();
      updateDisplayedGoodsList();
    } else {
      _handleManualMode(info);
      updateDisplayedGoodsList();
    }
  }

  // 获取新人好礼数据
  Future fetchRecentlyMarketingGoods() async {
    try {
      final result = await Network.getRecentlyMarketingGoods(9, 1, 20);
      if (result != null && result['goodsList'] != null) {
        Map goods = result['goodsList'];
        List list = goods['list'];
        List<NewZoneEntity> models = list.map((goods) {
          return NewZoneEntity.fromJson(goods);
        }).toList();
        newZoneGoodsList.assignAll(models); // 更新所有商品列表
      }
    } catch (error) {
      //print('新人好礼 Network request failed: $error');
    }
  }

  // 更新当前展示的商品列表
  void updateDisplayedGoodsList() {
    if (newZoneGoodsList.isEmpty) return;

    int start = _currentBatchStartIndex;
    int end = start + _itemsPerBatch;

    // 确保索引不会越界
    if (start >= newZoneGoodsList.length) {
      start = 0; // 如果超出范围，重置为从头开始
      end = _itemsPerBatch;
    }

    end = end.clamp(0, newZoneGoodsList.length);

    displayedGoodsList.assignAll(newZoneGoodsList.sublist(start, end));
    displayedGoodsList.refresh();

    _currentBatchStartIndex = end; // 更新下一批次的起始索引
  }

  // 换一批
  void refreshData() {
    updateDisplayedGoodsList();
  }

  // 手动模式处理
  Future<void> _handleManualMode(Map<String, dynamic> info) async {
    if (info['sub_entry'] == null || info['sub_entry'].isEmpty) {
      return;
    }
    String marketingId = info['sub_entry'][0]['marketingId'];
    await _getSecKillGoods(marketingId, info);
  }

// 获取活动商品列表的公用方法
  Future<void> _getSecKillGoods(String marketingId, Map<String, dynamic> info) async {
    try {
      Map<String, dynamic>? seckill = await getManualSecKillGoodsList(marketingId, '9');
      if (seckill == null || seckill.isEmpty) {
        return;
      }

      Map goods = seckill['goodsList'];
      List list = goods['list'];
      List<NewZoneEntity> models = list.map((goods) {
        return NewZoneEntity.fromJson(goods);
      }).toList();
      newZoneGoodsList.assignAll(models); // 更新所有商品列表
    } catch (e) {
      // print("获取活动商品列表失败");
    }
  }

  // 手动获取活动商品
  Future getManualSecKillGoodsList(String marketingId, String type) async {
    return await Network.manualQueryMarketingGoods(type, 1, 10, marketingId);
  }
}
